<?php

namespace App\Http\Utils\Currency;

use App\Exceptions\Exceptions\ValidationException;
use Payment\Client\Charge;
use Payment\Client\Notify;
use Payment\Config;
use Payment\Notify\PayNotifyInterface;

/**
 * Class WeChat
 * @package App\Http\Utils\Currency
 */
class WeChat extends ThirdPay
{
    /**
     * @return array
     */
    public function config()
    {
        return [
            'use_sandbox'  => false,
            'app_id'       => env('WECHAT_APPID'),
            'mch_id'       => env('WECHAT_MCHID'),
            'md5_key'      => env('WECHAT_APPKEY'),
            'app_cert_pem' => realpath('../config/Key/apiclient_cert.pem'),
            'app_key_pem'  => realpath('../config/Key/apiclient_key.pem'),
            'sign_type'    => 'MD5',
            'limit_pay'    => [
                'no_credit',
            ],
            'fee_type'     => 'CNY',
            'notify_url'   => env('WECHAT_NOTIFY'),
            'redirect_url' => isset($this->order->other['redirect_url']) ? $this->order->other['redirect_url'] : env('APP_URL'),
            'return_raw'   => false,
        ];
    }

    /**
     * @return array
     */
    public function payData()
    {
        return [
            'body'            => $this->order->body(),
            'subject'         => $this->order->title(),
            'order_no'        => $this->order->orderNum,
            'timeout_express' => $this->order->timeout(),
            'amount'          => $this->order->amount / 100,
            'return_param'    => 'test',
            'client_ip'       => $this->order->ip(),
            'scene_info'      => [
                'type'     => 'Wap',
                'wap_url'  => isset($this->order->other['wap_url']) ? $this->order->other['wap_url'] : env('APP_URL'),
                'wap_name' => isset($this->order->other['wap_name']) ? $this->order->other['wap_name'] : 'h5pay',
            ],
        ];
    }

    /**
     * @return mixed
     * @throws ValidationException
     */
    public function pay()
    {
        if (isset($this->order->other['redirect_url']) && isset($this->order->other['wap_url'])) {
            return Charge::run(Config::WX_CHANNEL_WAP, $this->config(), $this->payData());
        } else {
            throw new ValidationException([
                "支付宝支付参数other必须包含redirect_url(支付成功跳转地址)和wap_url(当前网站url)，可选参数(body，title，wap_name)"
            ]);
        }
    }

    /**
     * @param PayNotifyInterface $notify
     * @return array
     */
    public function notify(PayNotifyInterface $notify)
    {
        return Notify::run(Config::WX_CHARGE, $this->config(), $notify);
    }
}